const qiniuUploader = require('../../utils/qiniuUploader')
var uploadImage = require('../../js/uploadImg/uploadAliyun.js');
const{
  getFormattedAddress
} =require('../../api/third')
const{
  doTask
} =require('../../api/task')

const{
  addIssue
} =require('../../api/base')
const{
  pushProjects,pushMaintains,doAddTask
} =require('../../api/push')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPopup: false,
    is_submit: true,
    option:[],
    project_list:[],
    relationOption:[],
    maintain_list:[],
    do_type:0,
    capture:['camera'],
    project_id:0,
    note_text: '',
    task_id:0,
    maintainId:'',
    fileList: [],
    token:'',
    filePath: '',
    longitude: '',
    latitude: '',
    is_desc: 0,
    s_file_list: [],
    ruleForm: {
      all_project:false,
      project_id: '',
      maintain_id: '',
      do_uid: 0,
      radio_type: 1,
      is_desc: 0,
      finish_date: '',
      maintain_name_id: 0,
      project_select:'',
      name: ''
    },
    current_location_str: ''
  },
  selrelation(e) {
    let showPopup = true
    switch (e.target.dataset.name) {
      case 'project_select':
        this.data.option = []
        if (this.data.project_id == 0) {
          this.data.option = this.data.relationOption
        } else {
          showPopup =  false
        }
        break
      case 'maintain_select':
        this.data.option = []
        this.data.maintain_list.forEach((item) => {
          if (item.parentId == 0) {
            if(item.label == '90022') {
              if(this.data.do_type != '3') {
                this.data.option.push({ text: item.label, value: item.id , parent_id: item.parentId })
              }
            } else {
              this.data.option.push({ text: item.label, value: item.id , parent_id: item.parentId })
            }
          }
          
        })
        this.data.ruleForm['maintain_name_id'] = 0
        this.data.ruleForm['maintain_name_select'] = ''
        //this.data.option = this.data.maintain_list
        break
      case 'maintain_name_select':
        this.data.option = []
        this.data.maintain_list.forEach((item) => {
          console.log(item)
          if (item.id == this.data.ruleForm.maintain_id) {
            item.children.forEach((itemData)=>{
              this.data.option.push({ text: itemData.label, value: itemData.id , parent_id: itemData.parentId })
            })
            
          }
        })
        if (this.data.option.length < 1) {
          showPopup =  false
        }
        break
      default:
    }
    this.data.selName = e.target.dataset.name
    this.setData({
      showPopup: showPopup,
      option: this.data.option,
      ruleForm: this.data.ruleForm
    })
  },
  onCancel() {
    this.data.option = []
    this.setData({
      showPopup: false,
      option:[]
    })
  },
  onConfirm(event) {
    console.log(this.data.selName)
    console.log(event.detail)
    let arr = this.data.selName.split('.')
    let value =
      typeof event.detail.value == 'string'
        ? event.detail.value
        : event.detail.value.text
    if (arr.length > 1) {
      this.data.ruleForm[arr[0]][arr[1]] = value
    } else {
      this.data.ruleForm[this.data.selName] = value
      if (this.data.selName == 'project_select') {
        this.data.ruleForm['project_id'] = event.detail.value.value
      }else if (this.data.selName == 'maintain_select') {
        this.data.ruleForm['maintain_id'] = event.detail.value.value
      }else if (this.data.selName == 'maintain_name_select') {
        this.data.ruleForm['maintain_name_id'] = event.detail.value.value
      } else {
        this.data.ruleForm[this.data.selName+'_real'] = event.detail.value.value
      }
    }
    let ruleForm = this.data.ruleForm
    let showPopup = (this.data.showPopup = false)
    this.setData({ ruleForm, showPopup })
  },
  afterRead(event) {
    const { file } = event.detail; // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    this.uploadImg(file);
  },
  delete(event) {
    console.log(event)
    let imgDelIndex = event.detail.index
    let fileList = this.data.fileList
    let s_file_list = this.data.s_file_list
    fileList.splice(imgDelIndex,1)
    s_file_list.splice(imgDelIndex,1)
    console.log('删除图片的',fileList)
    this.setData({
        fileList,
        s_file_list
    })
  },
  didPressChooesImage(that) {
    initQiniu();
    // 微信 API 选文件
    wx.chooseImage({
        count: 1,
        success: function (res) {
          
        }
      })
  },
  uploadImg(file){
    wx.showLoading({
      title: '照片上传中~',
      mask: true
    })
    let scope = this
    var imgUrl =[];
    // 多张图片上传
    for(var i=0;i<file.length;i++){
      //var filePath = file[i].path;
      var filePath = file[i].path;
          uploadImage({
            filePath: filePath,
            dir: "lujinghua/",
            success: function (res) {
              const { fileList = [] } = scope.data;
              const sfileList = scope.data.s_file_list;
              sfileList.push({ url: filePath });
              fileList.push({ url: res.imageURL });
              scope.setData({
                src: filePath,
                s_file_list: sfileList,
                file_list: fileList,
                is_submit: false
              })
              wx.hideLoading({
                complete: (res) => {},
              })
            },
            fail: function (res) {
              wx.hideLoading({
                complete: (res) => {},
              })
              wx.showModal({
                title: "温馨提示", // 提示的标题
                content: "上传失败，请重试！", // 提示的内容
                showCancel: false, // 是否显示取消按钮，默认true
                confirmText: "确定", // 确认按钮的文字，最多4个字符
                confirmColor: "#576B95", // 确认按钮的文字颜色，必须是 16 进制格式的颜色字符串
                success: function (res) {
                  return
                }
              })
            }
          })
    }
  },
  submit(event) {
    this.setData({
      is_submit: true
    })
    if (this.data.fileList.length <= 0) {
      wx.showModal({
        title: "温馨提示", // 提示的标题
        content: "请选择图片", // 提示的内容
        showCancel: false, // 是否显示取消按钮，默认true
        confirmText: "确定", // 确认按钮的文字，最多4个字符
        confirmColor: "#576B95", // 确认按钮的文字颜色，必须是 16 进制格式的颜色字符串
        success: function (res) {
          return
        }
      })
      this.setData({
        is_submit: false
      })
      return
    } else {
      let is_undefined = false;
      this.data.fileList.forEach((child) => {
        if(child.url.indexOf('undefined') != -1) {
          is_undefined=true;
        }
      });
      if (is_undefined) {
        wx.showModal({
          title: "温馨提示", // 提示的标题
          content: "请重新选择图片", // 提示的内容
          showCancel: false, // 是否显示取消按钮，默认true
          confirmText: "确定", // 确认按钮的文字，最多4个字符
          confirmColor: "#576B95", // 确认按钮的文字颜色，必须是 16 进制格式的颜色字符串
          success: function (res) {
            return
          }
        })
        this.setData({
          is_submit: false
        })
        return

      }
    }
    if (this.data.do_type == 1) {
      var files = this.data.fileList;
      var fileUrls = [];
      for(var i=0;i<files.length;i++){
        fileUrls.push(files[i].url);
      }
      addIssue({imgPath:fileUrls.join(","),description:this.data.note_text}).then(res=>{
        var pages = getCurrentPages(); //当前页面
        var beforePage = pages[pages.length - 2]; //前一页
        wx.navigateBack({
          success: function () {
            beforePage.onPullDownRefresh(); // 执行前一个页面的onLoad方法
          }
        });
        this.setData({
          is_submit: false
        })
      })
    } else if(this.data.do_type == 3 || this.data.do_type == 4 || this.data.do_type == 5) {
      //判断是否为 3 拍照反馈  4 上班考勤  5 下班考勤
      if (this.data.fileList.length <= 0 || this.data.ruleForm.project_id == 0) {
        wx.showModal({
          title: "温馨提示", // 提示的标题
          content: "请选择必填项", // 提示的内容
          showCancel: false, // 是否显示取消按钮，默认true
          confirmText: "确定", // 确认按钮的文字，最多4个字符
          confirmColor: "#576B95", // 确认按钮的文字颜色，必须是 16 进制格式的颜色字符串
          success: function (res) {
            return
          }
        })
        this.setData({
          is_submit: false
        })
        return
      }
      if (this.data.do_type == 3) {
        if (this.data.ruleForm.maintain_id == 0) {
          this.data.ruleForm.maintain_id = 160000
        } else {
          if (this.data.ruleForm.maintain_name_id && this.data.ruleForm.maintain_name_id != 0) {
            this.data.ruleForm.maintain_id = this.data.ruleForm.maintain_name_id
          }
        }

      } else {
        this.data.ruleForm.maintain_id = ((this.data.do_type == 4)?90011:90012)
      }
      

      var fileListArray =[];
      this.data.fileList.forEach((item)=>{
        fileListArray.push(item.url);
      })

      doAddTask({projectId:this.data.ruleForm.project_id,doImgList:fileListArray.join(","),doTaskDesc:this.data.note_text,doTaskUid:app.userInfo.id,latLongItude:this.data.longitude +','+this.data.latitude,currentLocation:this.data.current_location_str,maintainId:this.data.ruleForm.maintain_id,taskType:0,isFinish:1,name:this.data.note_text}).then(res=>{
        //wx.switchTab({url: `/pages/index/index`})
        var pages = getCurrentPages(); //当前页面
        var beforePage = pages[pages.length - 3]; //前一页
        wx.navigateBack({
          delta: 2,
          success: function () {
            beforePage.onPullDownRefresh(); // 执行前一个页面的onLoad方法
          }
        });
        this.setData({
          is_submit: false
        })
      })
    }else {
      if (this.data.is_desc != '0') {
        if (this.data.note_text.length <= 0) {
          wx.showModal({
            title: "温馨提示", // 提示的标题
            content: "描述为必填项目", // 提示的内容
            showCancel: false, // 是否显示取消按钮，默认true
            confirmText: "确定", // 确认按钮的文字，最多4个字符
            confirmColor: "#576B95", // 确认按钮的文字颜色，必须是 16 进制格式的颜色字符串
            success: function (res) {
              return
            }
          })
          this.setData({
            is_submit: false
          })
          return
        }
      } 
      var fileListArray =[];
      this.data.fileList.forEach((item)=>{
        fileListArray.push(item.url);
      })
      const param = {id:this.data.task_id,doImgList:fileListArray.join(','),doTaskDesc:this.data.note_text,doTaskUid:app.userInfo.id,latLongItude:this.data.longitude+','+this.data.latitude,currentLocation:this.data.current_location_str,projectId:this.data.project_id,taskType:1,isFinish:1,maintainId:this.data.maintainId};
      doTask(param).then(res=>{
        //wx.switchTab({url: `/pages/index/index`})
        // var pages = getCurrentPages(); //当前页面
        // var beforePage = pages[pages.length - 2]; //前一页
        // wx.navigateBack({
        //   success: function () {
        //     beforePage.onPullDownRefresh(); // 执行前一个页面的onLoad方法
        //   }
        // });
        app.showTask = "2"
        wx.switchTab({  
          url:'/pages/index/index',
          success: function (e) {  
            var page = getCurrentPages().pop();  
            if (page == undefined || page == null) return;  
            page.onPullDownRefresh();  
          }

        });
        this.setData({
          is_submit: false
        })
      })

      this.setData({
        is_submit: false
      })
    }
    
  },
  onChange(event) {
    this.setData({
      note_text: event.detail,
    });
  },
  getLocationInfo() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        complete: (res) => {},
        fail: (res) => {},
        success: ({
          longitude: lng,
          latitude: lat
        }) => {
          resolve({
            lat,
            lng
          })
        },
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("加载任务...");
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.camera']) {
          wx.authorize({
            scope: 'scope.camera',
            success () {
            }
          })
        }
      }
    })

    this.data.ruleForm['project_select'] = options.pn
    this.data.ruleForm['project_id'] = options.id
    let ruleForm = this.data.ruleForm
      let s_file_list = [];
      let u_file_list = [];
      let is_submit = true
    if(options.s_file_list && options.s_file_list.length) {
      s_file_list = JSON.parse(decodeURIComponent(options.s_file_list));
      is_submit = false
    }
    if(options.u_file_list && options.u_file_list.length) {
      u_file_list = JSON.parse(decodeURIComponent(options.u_file_list));
      is_submit = false
    }

    this.setData({
      ruleForm,
      task_id: options.task_id,
      project_id: options.id,
      is_desc: options.is_desc,
      do_type:options.do_type,
      maintainId:options.maintainId,
      s_file_list,
      fileList:u_file_list,
      is_submit:is_submit,
      capture:options.do_type=='1'?['album', 'camera']:['camera']
    });
    
    if (options.do_type == 4 || options.do_type == 5) {
      wx.setNavigationBarTitle({
        title: (options.do_type == 4)?'上班考勤':'下班考勤' 
      })
      wx.showLoading({
        title: '数据加载中',
      })
      pushProjects({page:1}).then(res=>{
        console.log(res)
        this.setData({
          project_list: res.data,
          relationOption:res.data.map(item => {
            return { text: item.projectName, value: item.id };
          })
        })
      })
    }else if (options.do_type == 3) {
      wx.setNavigationBarTitle({
        title: "拍照反馈" 
      })
      wx.showLoading({
        title: '数据加载中',
      })
      pushProjects({}).then(res=>{
        console.log(res)
        this.setData({
          project_list: res.data,
          relationOption:res.data.map(item => {
            return { text: item.projectName, value: item.id };
          })
        })
        //获取一级分类
        pushMaintains({dictType :'fi_project_feedback_type'}).then(res=>{
          this.setData({
            maintain_list:res.data
          })
          console.log(res.data)
  
          wx.hideLoading({
            complete: (res) => {},
          })
          wx.hideNavigationBarLoading(); //完成停止加载图标
        })
        
      })

    } else {
      wx.setNavigationBarTitle({
        title: options.pn 
      })
    }
    this.getLocationInfo().then(res=> {
      getFormattedAddress({longitude:res.lng,latitude:res.lat}).then(response => {
        this.setData({
          longitude: res.lng,
          latitude: res.lat,
          current_location_str: response.data.currentLocationStr
        })
        wx.hideLoading({
          complete: (res) => {},
        })
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})